package io.github.yotta.dict.autoconfiguration;

import io.github.yotta.common.web.extension.LoginUserLoadProvider;
import io.github.yotta.common.web.extension.TenantResolveProvider;
import io.github.yotta.dict.api.service.SysDictService;
import io.github.yotta.dict.web.advice.SysDictExceptionHandler;
import io.github.yotta.dict.web.advice.SysDictResponseAdvice;
import io.github.yotta.dict.web.controller.SysDictReadController;
import io.github.yotta.dict.web.controller.SysDictWriteController;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(SysDictReadController.class)
@ConditionalOnBean(SysDictService.class)
public class SysDictWebConfiguration {

    @Bean
    public SysDictReadController sysDictReadController(
            SysDictService sysDictService,
            @Autowired(required = false) TenantResolveProvider tenantResolveProvider
    ) {
        if (tenantResolveProvider == null) {
            throw new NoSuchBeanDefinitionException("tenantResolveProvider must be implment ");
        }
        return new SysDictReadController(sysDictService, tenantResolveProvider) {
        };
    }

    @Bean
    public SysDictWriteController sysDictWriteController(
            SysDictService sysDictService,
            @Autowired(required = false) TenantResolveProvider tenantResolveProvider,
            @Autowired(required = false) LoginUserLoadProvider loginUserLoadProvider) {
        if (loginUserLoadProvider == null) {
            throw new NoSuchBeanDefinitionException("loginUserLoadProvider must be implment ");
        }
        return new SysDictWriteController(sysDictService, tenantResolveProvider, loginUserLoadProvider) {
        };
    }

    @Bean
    @ConditionalOnMissingBean(SysDictResponseAdvice.class)
    public SysDictResponseAdvice sysDictResponseAdvice() {
        return new SysDictResponseAdvice() {
        };
    }

    @Bean
    @ConditionalOnMissingBean(SysDictExceptionHandler.class)
    public SysDictExceptionHandler sysDictExceptionHandler() {
        return new SysDictExceptionHandler() {
        };
    }

}